package com.main.accountpermissionsmanagement.infrastructure.util;

import com.main.accountpermissionsmanagement.domain.account.repository.AccountRepository;
import jakarta.annotation.Resource;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicLong;

public class AccountGenerator {

    private final AtomicLong counter = new AtomicLong(0);

    // 线程安全的自增计数器

    public String generateAccount(String name,Long maxNumber) {
        if(maxNumber != null && maxNumber > 0){
            counter.set(maxNumber);
        }
        String prefix = "_";
        return getInitials(name) + prefix + formatNumber(counter.addAndGet(1));
    }

    // 格式化数字（小于1000补零，大于等于1000直接显示）
    private static String formatNumber(long num) {
        System.out.println("num:}"+num);
        return num < 1000 ?
                String.format("%03d", num) :
                String.valueOf(num);
    }

    // 汉字转拼音首字母（大写）
    private static String getInitials(String name) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder initials = new StringBuilder();
        for (char c : name.toCharArray()) {
            try {
                String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyin != null && pinyin.length > 0) {
                    initials.append(pinyin[0].charAt(0));
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                initials.append(c);
            }
        }
        return initials.toString();
    }
}
